package com.iceking.controller;

import com.iceking.dao.ArticleDao;
import com.iceking.dao.CategoryDao;
import com.iceking.model.Article;
import com.iceking.model.Category;
import com.iceking.model.PreArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

/**
 * Created by I on 2015/9/23.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleDao articleDao;

    @Autowired
    private CategoryDao categoryDao;

    @RequestMapping("/list")
    public String list(Model model) {
        List<Article> articleslist = articleDao.getAll();
        model.addAttribute("articleslist", articleslist);
        return "article/list";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        Article article = new Article();
        model.addAttribute("article", article);
        return "article/addArticle";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addArticleSubmit(PreArticle prearticle) {
        Article article = new Article();
        article.setTitle(prearticle.getTitle());
        article.setSendPerson(prearticle.getSendPerson());
        article.setContents(prearticle.getContents());

        String categories = prearticle.getCategories();
        if (null == categories) {
            System.out.println("----------------Null------------");
        } else if ("".equals(categories)) {
            System.out.println("----------------Empty-----------");
        } else {
            String[] cates = categories.split(",");
            for (String id : cates) {
                article.getCategories().add(categoryDao.getCategoryById(Long.parseLong(id)));
            }

        }

        article.setCreateTime(new Date());
        article.setReadTime(1);

        articleDao.add(article);
        return "redirect:/article/list";
    }

    @ModelAttribute("categories")
    Map<Long, String> Categories() {
        Map<Long, String> map = new HashMap<Long, String>();
        List<Category> list = categoryDao.getAll();
        for(Category category : list) {
            map.put(category.getId(), category.getCategoryTitle());
        }
        return map;
    }
}
